const shop = require('../../providers/dataAccess').shop;

const SkuService = function () {
    const _skuList = async (appId,productId) => {
      let szSql = "SELECT * FROM product_skus WHERE productId = ? AND appId = ?";
      let skus = await shop.query(szSql,[productId,appId]);
      if (skus && skus.length) {
         for (var index in skus) {
           let sku = skus[index];
           szSql = "SELECT sf.featureId,f.featureName,featureValueId,fv.featureValue from product_sku_features AS sf LEFT JOIN  features AS f ON sf.featureId = f.id LEFT JOIN feature_values AS fv ON sf.featureValueId = fv.id WHERE sf.productId = ? AND sf.skuId = ?";
           const features = await shop.query(szSql,[productId,sku.id]);
           sku.features = features;
         }
      }
      return skus;
    };


    const _updateSkuStock = async (appId,skuId,productId,count,type = 1) => {
      let szSql = "UPDATE product_skus SET salesCount = salesCount + ? WHERE id = ? AND productId = ? AND appId = ? AND totalNumber > salesCount + ?";
      if (type == 2) {
        szSql = "UPDATE product_skus SET salesCount = salesCount - ? WHERE id = ? AND productId = ? AND appId = ? AND salesCount >= ?";
      }
      let ret = await shop.query(szSql,[count,skuId,productId,appId,count]);
      return ret.affectedRows > 0 ? true : false;
    };

    const _getProduct = async (appId,productId,skuId) => {
      let szSql = "SELECT * FROM product_skus WHERE appId = ? AND productId = ? AND id = ?";
      let rows = await shop.query(szSql,[appId,productId,skuId]);
      return rows && rows.length ? rows[0] : {};
    }

    return {
      list: _skuList,
      updateSkuStock: _updateSkuStock,
      getProduct: _getProduct
    }
}();

module.exports = SkuService;
